package nonre.sgy.gencode.base.dao;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import nonre.sgy.gencode.base.GenericUtil;
import nonre.sgy.gencode.base.entity.BaseEntity;


public class BaseDaoImpl<En extends BaseEntity,K> implements BaseDao<En, K> {
	
	protected static final Logger LOG = LoggerFactory.getLogger(BaseDao.class);
	
	protected Class<En> enClazz;
	
	@PersistenceContext(name="entityManagerFactory")
	protected EntityManager em;
	
//	@Autowired
//	protected PlatformTransactionManager transactionManager;
	
	@SuppressWarnings("unchecked")
	public BaseDaoImpl(){
		try {
			enClazz = GenericUtil.getActualClass(this.getClass(), 0);
		} catch (Exception e) {
			LOG.error("basedao can not get entity clazz!", e);
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
//	@Transactional(propagation=Propagation.REQUIRED, value="transactionManager")
	public K save(En en) {
		em.persist(en);
		em.flush();
		return (K) en.getId();
	}

	@Override
	public En update(En en) {
		em.merge(en);
		em.flush();
		return en;
	}

	@Override
	public void delete(En en) {
		em.remove(em.contains(en)?en:em.merge(en));
	}

	@Override
	public void delById(K id) {
//		em.remove(em.find(clazz, id));
		em.remove(em.getReference(enClazz, id));
	}

	@Override
	public En findById(K id) {
		
		return em.find(enClazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<En> getAll() {
		String ql="from "+this.enClazz.getSimpleName()+" ";
		Query query=em.createQuery(ql);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<En> findList(String hql, Map<String, String> params) {
		Query query=em.createQuery(hql);
		Set<String> set=params.keySet();
		for (String key : set) {
			query.setParameter(key, params.get(key));
		}
		return query.getResultList();
	}

	@Override
	public void test() {
		System.out.println(this.getClass());
		System.out.println(this.enClazz);
		System.out.println(this.enClazz.getName());
		System.out.println(this.enClazz.getSimpleName());
	}

	

	

}
